using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;
using UnityEngine.UI;

public class SerialPortCommunication : MonoBehaviour
{
    private SerialPort serialPort;
    // 串口设置
    public string portName = "/dev/ttyCH341USB0";
    public int baudRate = 115200;
    public Parity parity = Parity.None;
    public int dataBits = 8;
    public StopBits stopBits = StopBits.One;
    public Text temperatureText;
    private float lastReadTime = 0f;
    private const float readDelay = 0.125f; // 读取数据的最小时间间隔

    // 用于存储当前读取的一组数据
    private List<string> currentDataGroup = new List<string>();
    // 标记是否正在读取一组数据
    private bool isReadingGroup = false;

    private void Start()
    {
        // 初始化串口
        serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

        try
        {
            serialPort.Open();
            Debug.Log("串口连接成功");
        }
        catch (Exception e)
        {
            Debug.LogError("串口连接失败: " + e.Message);
        }
    }

    private void Update()
    {
        if (serialPort.IsOpen)
        {
            if (Time.time - lastReadTime > readDelay)
            {
                try
                {
                    if (serialPort.BytesToRead > 0)
                    {
                        string incomingData = serialPort.ReadLine();

                        if (incomingData.StartsWith("@"))
                        {
                            isReadingGroup = true;
                            currentDataGroup.Clear();
                            currentDataGroup.Add(incomingData);
                        }
                        else if (isReadingGroup)
                        {
                            currentDataGroup.Add(incomingData);
                            if (incomingData.Contains("END"))
                            {
                                isReadingGroup = false;
                                DisplayDataGroup();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("读取数据时发生错误: " + e.Message);
                    // 可以添加重新初始化串口的逻辑，这里仅作示例，可根据实际情况调整
                    if (e.Message.Contains("The operation has timed out."))
                    {
                        TryReinitializeSerialPort();
                    }
                }
                lastReadTime = Time.time;
            }
        }
        else
        {
            Debug.LogWarning("串口未打开！");
        }
    }

    private void TryReinitializeSerialPort()
    {
        if (serialPort.IsOpen)
        {
            serialPort.Close();
        }
        try
        {
            serialPort.Open();
            Debug.Log("串口重新连接成功");
        }
        catch (Exception e)
        {
            Debug.LogError("串口重新连接失败: " + e.Message);
        }
    }

    private void DisplayDataGroup()
    {
        if (currentDataGroup.Count == 8)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string line in currentDataGroup)
            {
                sb.AppendLine(line);
            }
            Debug.Log(sb.ToString());
            temperatureText.text = sb.ToString();
        }
        else
        {
            Debug.LogWarning("接收到的数据组不完整，行数不为 7: " + currentDataGroup.Count);
        }
    }

    // 发送数据到串口，格式为 "%d %d"
    // 每次发送一个数据
    public void SendData(int a)
    {
        if (serialPort.IsOpen)
        {
            string data = string.Format("{0}", a);
            serialPort.WriteLine(data);
            Debug.Log("发送的数据: " + data);

            // 等待接收反馈并原样发送回去
            try
            {
                string incomingData = serialPort.ReadLine();
                Debug.Log("接收到的数据: " + incomingData);
            }
            catch (TimeoutException)
            {
                Debug.LogWarning("读取超时，没有接收到数据！");
            }
        }
        else
        {
            Debug.LogWarning("串口未打开！");
        }
    }

    private void OnApplicationQuit()
    {
        if (serialPort.IsOpen)
        {
            serialPort.Close();
            Debug.Log("串口已关闭");
        }
    }
}
